<template>
  <div class="container">
    <el-row :gutter="20" class="full-height">
      <!-- 左侧区域 -->
      <el-col :span="17" class="left-panel">
        <!-- 摄像头区域 -->
        <div v-if="isCameraOpen" class="camera-preview">
          <h2>摄像头实时画面</h2>
          <video
              ref="videoElement"
              autoplay
              playsinline
              class="video-element"
              v-show="!isLoadingCamera"
          ></video>
          <div v-if="isLoadingCamera" class="loading-message">
            <el-icon class="is-loading" :size="20"></el-icon>
            正在连接摄像头...
          </div>
          <div class="camera-controls">
            <el-button
                type="primary"
                @click="captureImage"
                :disabled="isLoadingCamera"
            >
              拍照
            </el-button>
            <el-button
                type="danger"
                @click="closeCamera"
            >
              关闭摄像头
            </el-button>
          </div>
        </div>
        <!-- 图片预览区域 -->
        <div v-if="selectedImage" class="image-preview">
          <h2>图片检测结果</h2>
          <el-image
              :src="selectedImage"
              fit="contain"
              style="max-height: 400px;"
              :preview-src-list="[selectedImage]"
          />
          <div class="image-info">
            <p>文件名: {{ fileName }}</p>
            <p>文件大小: {{ fileSize }} KB</p>
            <p>文件类型: {{ fileType }}</p>
          </div>
        </div>
        <!-- 视频预览区域 -->
        <div v-if="selectedVideo" class="video-preview">
          <h2>视频检测结果</h2>
          <video
              :src="selectedVideo"
              controls
              class="video-element"
              style="max-height: 400px;"
          ></video>
        </div>
        <!-- 输入框区域 -->
        <div class="input-area">
          <h2>大模型获取的文字消息</h2>
          <el-input
              v-model="inputText"
              type="textarea"
              :rows="4"
              placeholder="大模型获取的文字消息."
              clearable
          ></el-input>
        </div>
      </el-col>

      <!-- 右侧按钮区域 -->
      <el-col :span="7" class="right-panel">
        <div class="button-container">

          <div class="button-wrapper">
            <el-button
                type="primary"
                class="action-button"
                @click="triggerFileInput"
            >
              <el-icon><Picture /></el-icon>
              <span class="button-text">图片检测</span>
            </el-button>
            <input
                ref="fileInput"
                type="file"
                accept="image/*"
                style="display: none;"
                @change="handleImageSelect"
            >
          </div>

          <div class="button-wrapper">
            <el-button
                type="primary"
                class="action-button"
                @click="triggerVideoFileInput"
            >
              <el-icon><VideoCamera /></el-icon>
              <span class="button-text">视频检测</span>
            </el-button>
            <input
                ref="videoFileInput"
                type="file"
                accept="video/*"
                style="display: none;"
                @change="handleVideoSelect"
            >
          </div>

          <div class="button-wrapper">
            <el-button
                type="primary"
                class="action-button"
                @click="handleOpenCamera"
                :disabled="isCameraOpen || isLoadingCamera"
            >
              <el-icon><Camera /></el-icon>
              <span class="button-text">打开摄像头</span>
            </el-button>
          </div>

          <div class="button-wrapper">
            <el-button
                type="success"
                class="action-button"
                @click="handleSaveData"
            >
              <el-icon><FolderChecked /></el-icon>
              <span class="button-text">保存数据</span>
            </el-button>
          </div>

          <!-- 新增：场景下拉框 -->
          <div class="button-wrapper">
            <el-select
                v-model="scene"
                class="action-button custom-select"
                placeholder="请选择场景"
                style="width: 100%;"
            >
              <el-option
                  v-for="item in sceneOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </div>

          <div class="button-wrapper">
            <el-button
                type="danger"
                class="action-button"
                @click="handleCancel"
            >
              <el-icon><Close /></el-icon>
              <span class="button-text">取消</span>
            </el-button>
          </div>

        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import {
  Picture,
  VideoCamera,
  Camera,
  FolderChecked,
  Close
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

const inputText = ref('');

const fileInput = ref(null);
const videoFileInput = ref(null);
const videoElement = ref(null);
const selectedImage = ref(null);
const selectedVideo = ref(null);
const fileName = ref('');
const fileSize = ref(0);
const fileType = ref('');
const isCameraOpen = ref(false);
const isLoadingCamera = ref(false);

// 新增场景相关
const scene = ref('');
const sceneOptions = [
  { label: '墙上', value: '墙上' },
  { label: '路上', value: '路上' },
  { label: '室内', value: '室内' },
  { label: '手写', value: '手写' },
  { label: '其他', value: '其他' }
];

let mediaStream = null;

onMounted(() => {
  console.log('组件挂载完成');
});

const handleOpenCamera = async () => {
  try {
    isLoadingCamera.value = true;
    ElMessage.info('正在请求摄像头权限...');
    isCameraOpen.value = true;
    await nextTick();
    if (!videoElement.value) {
      throw new Error('视频元素未初始化');
    }
    mediaStream = await navigator.mediaDevices.getUserMedia({
      video: {
        width: { ideal: 1280 },
        height: { ideal: 720 },
        facingMode: 'user'
      }
    });
    videoElement.value.srcObject = mediaStream;
    selectedImage.value = null;
    selectedVideo.value = null;
    videoElement.value.onloadedmetadata = () => {
      videoElement.value.play()
          .then(() => {
            isLoadingCamera.value = false;
            ElMessage.success('摄像头已打开');
          })
          .catch(err => {
            isLoadingCamera.value = false;
            ElMessage.error('视频播放失败: ' + err.message);
            closeCamera();
          });
    };
    videoElement.value.onerror = () => {
      isLoadingCamera.value = false;
      ElMessage.error('视频播放出错');
      closeCamera();
    };
  } catch (error) {
    isLoadingCamera.value = false;
    console.error('摄像头访问错误:', error);
    ElMessage.error('摄像头访问失败: ' + (error.message || '未知错误'));
    closeCamera();
  }
};

const closeCamera = () => {
  if (mediaStream) {
    mediaStream.getTracks().forEach(track => track.stop());
    mediaStream = null;
  }
  if (videoElement.value) {
    videoElement.value.srcObject = null;
  }
  isCameraOpen.value = false;
  isLoadingCamera.value = false;
};

const captureImage = () => {
  if (!videoElement.value || !isCameraOpen.value || isLoadingCamera.value) return;
  try {
    const canvas = document.createElement('canvas');
    canvas.width = videoElement.value.videoWidth;
    canvas.height = videoElement.value.videoHeight;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(videoElement.value, 0, 0, canvas.width, canvas.height);

    selectedImage.value = canvas.toDataURL('image/png');
    fileName.value = `capture_${Date.now()}.png`;
    fileSize.value = (selectedImage.value.length / 1024).toFixed(2);
    fileType.value = 'image/png';

    closeCamera();
    ElMessage.success('拍照成功');
  } catch (error) {
    console.error('拍照失败:', error);
    ElMessage.error('拍照失败: ' + error.message);
  }
};

const triggerFileInput = () => {
  fileInput.value.click();
};

const handleImageSelect = (event) => {
  const file = event.target.files[0];
  if (!file) return;
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件');
    return;
  }
  fileName.value = file.name;
  fileSize.value = (file.size / 1024).toFixed(2);
  fileType.value = file.type;

  const reader = new FileReader();
  reader.onload = (e) => {
    selectedImage.value = e.target.result;
    selectedVideo.value = null;
  };
  reader.onerror = () => {
    ElMessage.error('读取图片失败');
  };
  reader.readAsDataURL(file);

  event.target.value = '';
};

const triggerVideoFileInput = () => {
  videoFileInput.value.click();
};

const handleVideoSelect = (event) => {
  const file = event.target.files[0];
  if (!file) return;
  if (!file.type.startsWith('video/')) {
    ElMessage.error('请选择视频文件');
    return;
  }
  selectedVideo.value = URL.createObjectURL(file);
  selectedImage.value = null;
  fileName.value = file.name;
  fileSize.value = (file.size / 1024).toFixed(2);
  fileType.value = file.type;

  event.target.value = '';
};

const handleSaveData = () => {
  if (!selectedImage.value && !selectedVideo.value) {
    ElMessage.warning('没有可保存的数据');
    return;
  }
  ElMessage.success('数据保存成功');
  // 这里可以用 scene.value 获取选中的场景
  console.log('当前场景：', scene.value);
};

const handleCancel = () => {
  closeCamera();
  selectedImage.value = null;
  selectedVideo.value = null;
  ElMessage.info('操作已取消');
};
</script>

<style scoped>
.container {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
}
.full-height {
  height: 100%;
}
.left-panel {
  background-color: white;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}
.image-preview, .video-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}
.image-info {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
  width: 100%;
  max-width: 500px;
}
.right-panel {
  background-color: #e6f7ff;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
}
.button-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding: 20px;
}
.button-wrapper {
  display: flex;
  align-items: center;
  width: 100%;
}
.action-button {
  width: 100%;
  height: 56px;
  font-size: 16px;
  justify-content: flex-start;
  border-radius: 8px;
  margin: 0;
  padding-left: 16px;
  background-color: white;
  border: 1px solid #d9d9d9;
}
.action-button.el-button--primary {
  color: #409EFF;
  border-color: #409EFF;
}
.action-button.el-button--success {
  color: #67C23A;
  border-color: #67C23A;
}
.action-button.el-button--danger {
  color: #F56C6C;
  border-color: #F56C6C;
}
.button-text {
  margin-left: 8px;
  flex-grow: 1;
  text-align: left;
}
.video-element {
  width: 100%;
  max-height: 400px;
  background-color: #000;
  border-radius: 4px;
  display: block;
}
.camera-preview {
  display: flex;
  flex-direction: column;
  gap: 15px;
}
.camera-controls {
  display: flex;
  gap: 10px;
  justify-content: center;
}
.loading-message {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #666;
  gap: 10px;
  font-size: 16px;
}
@media (max-width: 768px) {
  .left-panel, .right-panel {
    width: 100% !important;
  }
  .button-container {
    flex-direction: row;
    flex-wrap: wrap;
  }
  .action-button {
    width: calc(50% - 12px);
  }
}
.input-area {
  margin-top: auto; /* 保证在左边底部 */
  padding-top: 20px;
}
.input-area h2 {
  margin-bottom: 10px;
  font-size: 18px;
}
.custom-select {
  width: 100% !important;
  height: 56px !important;
  line-height: 56px;
}
.custom-select :deep(.el-input__wrapper) {
  border: 2px solid #ffbe00 !important;   /* 明亮黄 */
  border-radius: 12px;
  height: 56px;
  box-sizing: border-box;
}
.custom-select :deep(.el-input__inner) {
  height: 56px;
  font-size: 16px;
  line-height: 56px;
  background: #fff;
}
</style>
